/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package com.je.bpm.engine.impl.persistence.entity;

import com.je.bpm.engine.history.HistoricVariableInstance;
import com.je.bpm.engine.impl.HistoricVariableInstanceQueryImpl;
import com.je.bpm.engine.impl.Page;
import com.je.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import com.je.bpm.engine.impl.history.HistoryLevel;
import com.je.bpm.engine.impl.persistence.entity.data.DataManager;
import com.je.bpm.engine.impl.persistence.entity.data.HistoricVariableInstanceDataManager;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;


public class HistoricVariableInstanceEntityManagerImpl extends AbstractEntityManager<HistoricVariableInstanceEntity> implements HistoricVariableInstanceEntityManager {

    private static final String[] NO_GARBAGE_VAR_NAMES = new String[]{"oneBallotUserId", "datas"};

    protected HistoricVariableInstanceDataManager historicVariableInstanceDataManager;

    public HistoricVariableInstanceEntityManagerImpl(ProcessEngineConfigurationImpl processEngineConfiguration, HistoricVariableInstanceDataManager historicVariableInstanceDataManager) {
        super(processEngineConfiguration);
        this.historicVariableInstanceDataManager = historicVariableInstanceDataManager;
    }

    @Override
    protected DataManager<HistoricVariableInstanceEntity> getDataManager() {
        return historicVariableInstanceDataManager;
    }

    @Override
    public HistoricVariableInstanceEntity copyAndInsert(VariableInstanceEntity variableInstance) {
        HistoricVariableInstanceEntity historicVariableInstance = historicVariableInstanceDataManager.create();
        historicVariableInstance.setId(variableInstance.getId());
        historicVariableInstance.setProcessInstanceId(variableInstance.getProcessInstanceId());
        historicVariableInstance.setExecutionId(variableInstance.getExecutionId());
        historicVariableInstance.setTaskId(variableInstance.getTaskId());
        historicVariableInstance.setRevision(variableInstance.getRevision());
        historicVariableInstance.setName(variableInstance.getName());
        historicVariableInstance.setVariableType(variableInstance.getType());

        copyVariableValue(historicVariableInstance, variableInstance);

        Date time = getClock().getCurrentTime();
        historicVariableInstance.setCreateTime(time);
        historicVariableInstance.setLastUpdatedTime(time);

        insert(historicVariableInstance);

        return historicVariableInstance;
    }

    @Override
    public void copyVariableValue(HistoricVariableInstanceEntity historicVariableInstance, VariableInstanceEntity variableInstance) {
        historicVariableInstance.setTextValue(variableInstance.getTextValue());
        historicVariableInstance.setTextValue2(variableInstance.getTextValue2());
        historicVariableInstance.setDoubleValue(variableInstance.getDoubleValue());
        historicVariableInstance.setLongValue(variableInstance.getLongValue());

        historicVariableInstance.setVariableType(variableInstance.getType());
        if (variableInstance.getByteArrayRef() != null) {
            historicVariableInstance.setBytes(variableInstance.getBytes());
        }

        historicVariableInstance.setLastUpdatedTime(getClock().getCurrentTime());
    }

    @Override
    public void delete(HistoricVariableInstanceEntity entity, boolean fireDeleteEvent) {
        super.delete(entity, fireDeleteEvent);

        if (entity.getByteArrayRef() != null) {
            entity.getByteArrayRef().delete();
        }
    }

    @Override
    public void deleteHistoricVariableInstanceByProcessInstanceId(final String historicProcessInstanceId) {
        if (getHistoryManager().isHistoryLevelAtLeast(HistoryLevel.ACTIVITY)) {
            List<HistoricVariableInstanceEntity> historicProcessVariables = historicVariableInstanceDataManager.findHistoricVariableInstancesByProcessInstanceId(historicProcessInstanceId);
            for (HistoricVariableInstanceEntity historicProcessVariable : historicProcessVariables) {
                delete(historicProcessVariable);
            }
        }
    }

    @Override
    public void deleteGarbageHistoricVariableInstanceByProcessInstanceId(final String historicProcessInstanceId) {
        List<HistoricVariableInstanceEntity> historicProcessVariables = historicVariableInstanceDataManager.
                findHistoricVariableInstancesByProcessInstanceId(historicProcessInstanceId);
        for (HistoricVariableInstanceEntity historicProcessVariable : historicProcessVariables) {
            if (!Arrays.asList(NO_GARBAGE_VAR_NAMES).contains(historicProcessVariable.getName())) {
                delete(historicProcessVariable);
            }
        }
    }

    @Override
    public long findHistoricVariableInstanceCountByQueryCriteria(HistoricVariableInstanceQueryImpl historicProcessVariableQuery) {
        return historicVariableInstanceDataManager.findHistoricVariableInstanceCountByQueryCriteria(historicProcessVariableQuery);
    }

    @Override
    public List<HistoricVariableInstance> findHistoricVariableInstancesByQueryCriteria(HistoricVariableInstanceQueryImpl historicProcessVariableQuery, Page page) {
        return historicVariableInstanceDataManager.findHistoricVariableInstancesByQueryCriteria(historicProcessVariableQuery, page);
    }

    @Override
    public void updateDatas(String executionId, String value) {
        historicVariableInstanceDataManager.updateDatas(executionId, value);
    }

    @Override
    public HistoricVariableInstanceEntity findHistoricVariableInstanceByVariableInstanceId(String variableInstanceId) {
        return historicVariableInstanceDataManager.findHistoricVariableInstanceByVariableInstanceId(variableInstanceId);
    }

    @Override
    public void deleteHistoricVariableInstancesByTaskId(String taskId) {
        if (getHistoryManager().isHistoryLevelAtLeast(HistoryLevel.ACTIVITY)) {
            List<HistoricVariableInstanceEntity> historicProcessVariables = historicVariableInstanceDataManager.findHistoricVariableInstancesByTaskId(taskId);
            for (HistoricVariableInstanceEntity historicProcessVariable : historicProcessVariables) {
                delete((HistoricVariableInstanceEntity) historicProcessVariable);
            }
        }
    }

    @Override
    public List<HistoricVariableInstance> findHistoricVariableInstancesByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) {
        return historicVariableInstanceDataManager.findHistoricVariableInstancesByNativeQuery(parameterMap, firstResult, maxResults);
    }

    @Override
    public long findHistoricVariableInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
        return historicVariableInstanceDataManager.findHistoricVariableInstanceCountByNativeQuery(parameterMap);
    }


    public HistoricVariableInstanceDataManager getHistoricVariableInstanceDataManager() {
        return historicVariableInstanceDataManager;
    }


    public void setHistoricVariableInstanceDataManager(HistoricVariableInstanceDataManager historicVariableInstanceDataManager) {
        this.historicVariableInstanceDataManager = historicVariableInstanceDataManager;
    }

}
